package com.wh.common.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * @author luweije
 */
public class TraceUtil {

    private static final String TRACE_ID = "traceId";

    public static String getTraceIdFromMdc() {
        return MDC.get(TRACE_ID);
    }

    public static void startTraceFromHttp(HttpServletRequest request) {
        String traceId = request.getHeader(TRACE_ID);
        setTraceId(traceId);
    }

    private static void setTraceId(String traceId) {
        if (StringUtils.isBlank(traceId)) {
            traceId = UUID.randomUUID().toString().replace("-", "");
        }
        MDC.put(TRACE_ID, traceId);
    }

}
